package com.xydtech.common.utils.rsa;

/**
 * 创建时间：2023/2/22 10:39
 * 项目名称：WechatSemApi
 * @author JHON
 * @version 1.0
 * @since JDK 1.8.0_201
 * 文件名称：MyResponseBodyAdvice
 * 类说明：实现接口，定义返回结果的加密。（jsondata就是统一返回的实体类）

 */


import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@Slf4j
@ControllerAdvice(basePackages = {"com.xydtech.ecard", "com.xydtech.appapi"})
public class MyResponseBodyAdvice implements ResponseBodyAdvice<ResponseModel> {

    /**
     * 判断支持的类型
     *
     * @param returnType
     * @param converterType
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        RsaRequest serializedField = returnType.getMethodAnnotation(RsaRequest.class);
        if (serializedField == null) {
            return false;
        }
        return serializedField.result();
    }

    /**
     * 对于结果进行加密
     *
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     */
    @Override
    public ResponseModel beforeBodyWrite(ResponseModel body, MethodParameter returnType, org.springframework.http.MediaType selectedContentType,
                                    Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Object data = body.getData();
        Integer code = body.getCode();
        if (data == null || ResultStatus.SUCCESS.getCode() != code) {
            return body;
        }
        String dataStr = data.toString();
        String result = RsaUtils.encryptLongByPrivateKey(dataStr);
        body.setData(result);
        return body;
    }

}